package org.example.videotran.utils;

import io.jsonwebtoken.*;
import org.example.videotran.exception.AppException;
import org.example.videotran.exception.AppExceptionCodeMsg;
import org.example.videotran.pojo.User;

import java.util.Date;
import java.util.UUID;


public class JwtToken {

    private static long time = 1000*60*60*24;//token有效期一天
    private static String signature = "admin";



    public static String createToken(User userDto){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //Header
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //payload
                .claim("phone",userDto.getPhone())
                .claim("uid",userDto.getUid())
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
//        System.out.println(jwtToken);
        return jwtToken;
    }

    // 解析 token，获取电话
    public static String extractPhone(String token) {
        Claims claims = null;
        try {
            JwtParser jstParser = Jwts.parser();
            Jws<Claims> claimsJws = jstParser.setSigningKey(signature).parseClaimsJws(token);
            claims = claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new AppException(AppExceptionCodeMsg.OVERDUE_TOKEN);
        }
        return claims.get("phone").toString();
    }

    public static String extractUid(String token) {
        JwtParser jstParser = Jwts.parser();
        Jws<Claims> claimsJws = jstParser.setSigningKey(signature).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims.get("uid").toString();
    }

    // 验证 token 是否有效
    public static boolean isTokenExpired(String token) {
        Date expiration = Jwts.parser()
                .setSigningKey(signature)
                .parseClaimsJws(token)
                .getBody()
                .getExpiration();
        return expiration.before(new Date());
    }

    // 验证 token 的合法性
    public static boolean validateToken(String token, String username) {
        return (username.equals(extractPhone(token)) && !isTokenExpired(token));
    }

}
